package com.example.config;

import com.example.annotation.NotBlankPattern;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraints.Pattern;
import java.util.regex.Matcher;
import java.util.regex.PatternSyntaxException;

/**
 * @author zhaiyue
 * @date 2022/7/18
 */

public class NotBlankPatternVaildator implements ConstraintValidator<NotBlankPattern, CharSequence> {

    //private static final Log log = LoggerFactory.make();

    private java.util.regex.Pattern pattern;

    @Override
    public void initialize(NotBlankPattern parameters) {
        Pattern.Flag[] flags = parameters.flags();
        int intFlag = 0;
        for ( Pattern.Flag flag : flags ) {
            intFlag = intFlag | flag.getValue();
        }

        try {
            pattern = java.util.regex.Pattern.compile( parameters.regexp(), intFlag );
        }
        catch (PatternSyntaxException e) {
          //  throw log.getInvalidRegularExpressionException( e );
        }
    }

    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext constraintValidatorContext) {
        if (!StringUtils.hasText(value)) {
            return true;
        }
        Matcher m = pattern.matcher( value );
        return m.matches();
    }
}
